import React, { Component, PropTypes } from "react";
import Condition from "components/condition";
import { messages, queryCurrencyPrecision } from "share/common";
import { Button, Row, Col, Spin, message } from "antd"
import Table from "components/table";
import moment from "moment";
import borrowService from "../../borrow-and-return.service";
import SlideFrame from "components/slide-frame";
import ViewLine from "../../template/view-line";
import statisticsPNG from "images/loan-billing/statistics.png";
import addLoan from "../../template/add-loan";
import DebtModal from "../../template/debt-modal";
import EditAudit from "../../../financial-management/new-finance-audit/components/edit-audit";
import menuRoute from "routes/menuRoute";
import contractService from '../../../contract/contract.service';
import Importer from "components/template/importer/index";
import { connect } from 'react-redux';

const { If } = Condition;

@connect(mapStateToProps)
class SlideLoanLine extends Component {

  state = {
    loanTableData: [], //列表数据
    tableLoading: false,
    expandedRowKeys: [],
    debtVisible: false,
    debtInfo: {}
  };

  componentDidMount() {
    this.getList();
  }

  getList() {
    const { info, pathname } = this.context;
    if (info.id) {
      this.setState({ tableLoading: true });
      let isFinance = pathname.indexOf('financial-management') > -1 || pathname.indexOf('pay-workbench') > -1;
      borrowService.getLoanTable(info.id, isFinance).then(res => {
        this.setState({ tableLoading: false, loanTableData: res.data, expandedRowKeys: [] })
      }).catch(e => {
        message.error(e.response.data.message);
        this.setState({ tableLoading: false });
      })
    }
  };

  handleAddLoan = () => {
    const { info, form } = this.context;
    SlideFrame.open({
      title: messages('finance-1.key38')/*新建借款计划*/,
      content: addLoan,
      params: {
        info,
        recordInfo: '',
        formInfo: form
      },
      afterClose: value => value && this.refreshTable()
    }, this)
  };

  refreshTable = () => {
    this.getList();
  };

  loanEnum = {
    "ONLINE_PAYMENT": messages('finance-1.key116')/*线上*/,
    "OFFLINE_PAYMENT": messages('finance-1.key117')/*线下*/,
    "EBANK_PAYMENT": messages('finance-1.key118')/*落地文件*/
  };

  columns = [
    {
      title: messages('common.sequence')/*序号*/, dataIndex: 'index', width: 48,
      className: 'table-row-left-align',
      render: (value, record, index) => index + 1
    },
    { title: messages('common.currency')/*币种*/, dataIndex: 'currencyCode', width: 48 },
    {
      title: messages('finance-1.key16')/*借款金额*/, dataIndex: 'amount',
      render: (value,record) => this.filterMoney(value, queryCurrencyPrecision(record.currencyCode))
    },
    { title: messages('finance-1.key17')/*借款类型*/, dataIndex: 'loanTypeName' },
    {
      title: messages('finance-1.key119')/*收款方类型*/, dataIndex: 'payeeType',
      render: value => value === 1002 ? messages('finance-1.key19')/*员工*/ : messages('finance-1.key20')/*供应商*/
    },
    {
      title: messages('finance-1.key120')/*收款方*/, dataIndex: 'payeeName',
      render: (value, record) => (
        <div>
          {value}
          <div>
            <img
              src={statisticsPNG}
              onClick={(e) => this.handleImgClick(e, record)}
              style={{ width:'18px', height:'18px', display: 'inline-block', float: 'left', marginTop: '2px' }}
            />
            {messages('finance-1.key121')/*欠款统计*/}
          </div>
        </div>
      )
    },
    {
      title: messages('finance-1.key21')/*收款账户*/, dataIndex: 'payeeAccountName',
      render: (value, record) => (
        <div>
          <div>{messages('finance-1.key22')/*户名*/}:{value}</div>
          <div>{messages('finance-1.key23')/*账户*/}:{record.payeeAccountNumber}</div>
        </div>
      )
    },
    {
      title: messages('finance-1.key24')/*借款属性*/, dataIndex: 'planedRepaymentDate', hide: true,
      render: (value, record) => (
        <div>
          <div>{messages('finance-1.key25')/*计划还款日期*/}:{value ? moment(value).format('YYYY-MM-DD') : '-'}</div>
          <div>{messages('finance-1.key26')/*付款方式类型*/}:{this.loanEnum[record.paymentType]}</div>
        </div>
      )
    },
    {
      title: messages('finance-1.key27')/*备注*/, dataIndex: 'remark',
      render: value => value ? value : '-'
    }
  ];

  renderContent = record => {
    const { rowLoading } = this.state;
    let rowInfo = record._info;
    const { contractAssociatedDTO } = rowInfo || {};
    return rowInfo ? (
      <div
        style={{
          backgroundColor: 'rgb(227, 228, 230)',
          margin: '-8px -12px',
          padding: '8px 12px'
        }}
      >
        <Row>
          <Col span={3}>{messages('finance-1.key46')/*提交金额属性*/}</Col>
          <Col span={21}>
            <span>{messages('finance-1.key47')/*提交本币金额*/}:{rowInfo.baseCurrencyCode} {rowInfo.baseAmount ? this.filterMoney(rowInfo.baseAmount,queryCurrencyPrecision(rowInfo.baseCurrencyCode),true) : '-'}</span>
            <span style={{marginLeft:'10px'}}>{messages('common.currency.rate')/*汇率*/}:{rowInfo.currencyRate ? rowInfo.currencyRate : '-'}</span>
            <span style={{marginLeft:'10px'}}>{messages('finance-1.key48')/*汇率日期*/}:{rowInfo.currencyRateApplyDate ? moment(rowInfo.currencyRateApplyDate).format('YYYY-MM-DD') : '-'}</span>
          </Col>
        </Row>
        <Row>
          <Col span={3}>{messages('finance-1.key49')/*关联申请单*/}</Col>
          <Col span={21}>
            <span>{messages('finance-1.key50')/*申请单编号*/}:{rowInfo.refApplicationBusinessCode ? rowInfo.refApplicationBusinessCode: '-'}</span>
            <span style={{marginLeft:'10px'}}>{messages('finance-1.key51')/*申请单金额*/}:{rowInfo.refApplicationCurrencyCode ? rowInfo.refApplicationCurrencyCode: '-'}&nbsp;&nbsp;{rowInfo.refApplicationAmount ? this.filterMoney(rowInfo.refApplicationAmount,queryCurrencyPrecision(rowInfo.refApplicationCurrencyCode),true) : '-'}</span>
          </Col>
        </Row>
        {
          contractAssociatedDTO && Object.keys(contractAssociatedDTO).length > 0 && (
            <Row>
              <Col span={3}>{messages('finance-1.key52')/*关联合同*/}:</Col>
              <Col span={21}>
                <span>{messages('finance-1.key53')/*合同名称*/}:{contractAssociatedDTO.contractName}</span>
                <span style={{marginLeft:'10px'}}>
                  {messages('finance-1.key54')/*合同编号*/}:
                  <a onClick={() => this.handleContractClick(contractAssociatedDTO.contractHeaderId)}>{contractAssociatedDTO.contractNumber}</a>
                </span>
                <span style={{marginLeft:'10px'}}>{messages('finance-1.key55')/*计划付款日期*/}:{moment(contractAssociatedDTO.dueDate).format('YYYY-MM-DD')}</span>
                <span style={{marginLeft:'10px'}}>{messages('finance-1.key56')/*计划付款行行号*/}:{contractAssociatedDTO.lineNumber}</span>
              </Col>
            </Row>
          )
        }
        <Row>
          <Col span={3}>{messages('finance-1.key57')/*付款日志*/}:</Col>
          <Col span={21}>
            {
              rowInfo.transactionDetailDTOList.map(item => {
                return <div>
                  <span>{messages('finance-1.key58')/*付款金额*/}:{`${item.curreny}  ${this.filterMoney(item.amount,queryCurrencyPrecision(item.curreny),true)}`}</span>
                  <span style={{marginLeft:'10px'}}>{messages('common.currency.rate')/*汇率*/}:{item.exchangeRate}</span>
                  <span style={{marginLeft:'10px'}}>{messages('finance-1.key48')/*汇率日期*/}:{moment(item.payDate).format('YYYY-MM-DD')}</span>
                </div>
              })
            }
          </Col>
        </Row>
      </div>
    ) : <Spin spinning={rowLoading} />
  };

  handleContractClick =async id => {
    const res = await contractService.getContractHeaderInfo(id);
    window.open((window.ISIE9 ? '#' : '') + menuRoute.getRouteItem('contract-detail').url.replace(':entityOID', res.data.documentOid));
  };

  renderAllExpandedRow = (expanded, record) => {
    const { loanTableData, expandedRowKeys } = this.state;
    if (expanded) {
      expandedRowKeys.push(record.id);
      if (!loanTableData.find(item => item.id === record.id)._info) {
        this.setState({ rowLoading: true });
        borrowService.getLineInfo(record.id).then(res => {
          record._info = res.data;
          this.setState({ rowLoading: false });
        }).catch(e => {
          message.error(e.response.data.message);
          this.setState({ rowLoading: false });
        })
      }
    } else {
      expandedRowKeys.delete(record.id);
    }
    this.setState({ expandedRowKeys });
  };

  handleRowClick = record => {
    const { pathname } = this.context;
    if (pathname.indexOf('approve') || pathname.indexOf('finance-audit')) {
      SlideFrame.open({
        content: ViewLine,
        params: {
          viewId: record.id
        },
        title: messages('finance-1.key45')/*查看借款计划*/
      }, this)
    }
  };

  handleImgClick = (e, record) => {
    e.stopPropagation();
    this.setState({
      debtVisible: true,
      debtInfo: record
    })
  };

  editRecord = (e, record) => {
    const { operator, info, form, getInfo } = this.context;
    e.stopPropagation();
    if (operator) {
      SlideFrame.open({
        title: messages('finance-1.key59')/*编辑借款计划*/,
        content: addLoan,
        width: 800,
        params: {
          info,
          recordInfo: record.id,
          formInfo: form
        },
        afterClose: value => value && this.refreshTable()
      }, this)
    } else {
      SlideFrame.open({
        title: messages('finance-1.key122')/*编辑借款行*/,
        content: EditAudit,
        params: {
          record: record,
          formInfo: form,
          info,
          method: borrowService.editBorrowAudit,
          methodParams: { id: record.id, companyId: info.companyId }
        },
        afterClose: value => value && getInfo()
      }, this)
    }
  };

  deleteRecord = (e, record) => {
    e.stopPropagation();
    borrowService.deleteLoanLine(record.id).then(() => {
      this.getList();
    }).catch(e => {
      message.error(e.response.data.message);
    })
  };

  render() {
    const { operator, info, form, isWaitForAudit, pathname } = this.context;
    const { loanTableData, tableLoading, expandedRowKeys, debtVisible, debtInfo } = this.state;
    const { columns } = this;
    const { customFormPropertyMap = {} } = form;
    const { options: { auditBaseConfig } } = this.props;
    (operator || (isWaitForAudit && (pathname.indexOf('finance-audit') && auditBaseConfig.reviewEditSuitable && auditBaseConfig.reviewEditEnable)))
    && !columns.find(item => item.dataIndex === 'operate') && columns.push({
      title: messages('common.operation')/*操作*/, dataIndex: 'operate',
      render: (value, record) => (
        <div>
          <a onClick={e => this.editRecord(e,record)}>{messages('common.edit')/*编辑*/}</a>
          {
            operator && (
              <span>
                <span className="ant-divider"/>
                <a onClick={e => this.deleteRecord(e,record)}>{messages('common.delete')/*删除*/}</a>
              </span>
            )
          }
        </div>
      )
    });
    return (
      <div style={{ marginTop: '20px' }}>
        <div className='slide-expense-report-detail-expense'>
          <div style={{ height: '32px', marginBottom: '10px' }}>
            <If value={operator}>
              <div>
                <Button
                  type='primary'
                  onClick={this.handleAddLoan}
                  style={{ marginRight: '8px' }}
                  disabled={customFormPropertyMap['multi.loan'] === 'false' && loanTableData.length > 0}
                >
                  {messages('finance-1.key42')/*新建借款信息*/}
                </Button>
                <If value={customFormPropertyMap['multi.loan'] !== 'false' && info.type === 2006}>
                  <Importer
                    btnName={messages('finance-1.key43')/*导入借款信息*/}
                    btnProps={{type: 'default'}}
                    templateOptions={{
                      templateList: [{
                        templateName: messages('finance-1.key44')/*借款信息模板*/,
                        downloadUrl: `/api/loan/line/batchimport/template/download`,
                        downloadParams: { setOfBookId: info.setOfBooksId }
                      }]
                    }}
                    onOK={this.refreshTable}
                    errorTableData={data => Importer.getUploadResult(data)}
                    uploadOptions={{
                      uploadUrl: `/api/loan/line/line/uploading?loanBillOid=${info.loanBillOID}`,
                      listenUrl: '/api/loan/line/query/error'
                    }}
                    uploadResultOptions={{
                      shouldDownloadErrorInfo: true,
                      errorUrl: '/api/loan/line/download/error',
                      getErrorTableVisible: uploadResult => uploadResult && uploadResult.failureEntities > 0
                    }}
                  />
                </If>
              </div>
            </If>
          </div>
          <div className='slide-expense-report-detail-expense-list-container'>
            <Table
              loading={tableLoading}
              className='slide-expense-report-detail-expense-list-table'
              columns={columns}
              dataSource={loanTableData}
              rowKey="id"
              showUtils
              pagination={false}
              utilsConfig={{ style: { right: 0 } }}
              expandedRowKeys={expandedRowKeys}
              expandedRowRender={this.renderContent}
              scroll={{x:  true}}
              onExpand={this.renderAllExpandedRow}
              onRow={record => ({onClick: () => this.handleRowClick(record)})}
            />
          </div>
        </div>
        <DebtModal
          visible={debtVisible}
          info={debtInfo}
          loanInfo={info}
          close={() => {
            this.setState({debtVisible: false, debtInfo: {}})
          }}
        />
      </div>
    )
  }

  static contextTypes = {
    operator: PropTypes.bool,
    info: PropTypes.object,
    form: PropTypes.object,
    pathname: PropTypes.string,
    isWaitForAudit: PropTypes.bool,
    getInfo: PropTypes.func
  }

}

function mapStateToProps (state) {
  return {
    options: state.login.options
  }
}

export default SlideLoanLine
